package org.fxcontainer.actions
{
	import com.developmentarc.core.actions.actions.AbstractAction;
	
	import flash.events.Event;
	
	import mx.core.UIComponent;
	
	import org.fxcontainer.commands.ControlAppearCommand;
	import org.fxcontainer.controls.IControl;
	import org.fxcontainer.registry.ControlRegistry;
	import org.fxcontainer.structure.IPage;
	
	/**
	 * Action to perform indication that control is appeared on a page.<br/>
	 * Also provides control registration within <code>ControlRegistry</code>. 
	 * @author Izzet_Mustafayev
	 */
	public class ControlAppearAction extends AbstractAction
	{
		/**
		 * The <code>ControlAppearAction</code> constructor. 
		 * <br/>Creates action instance and registers applyable command. 
		 */
		public function ControlAppearAction()
		{
			super();
			this.addCommand(ControlAppearCommand.CTRL_APPEAR_CMD);
		}
		
		/**
		 * Registers <code>IControl</code> within control register to a specific page. 
		 * @param command the command triggered registering process.
		 */
		override public function applyAction(_command:Event):void 
		{
			if (null != _command && _command is ControlAppearCommand){
				var command:ControlAppearCommand = _command as ControlAppearCommand;
				var component:UIComponent = UIComponent(command.control);
				var page:IPage = findControlPage(component);
				if (null != page){
					//register control within page
					ControlRegistry.register(page, IControl(component));
				}
			}
		}
		
		private function findControlPage(component:UIComponent):IPage
		{
			var page:IPage = null;
			if (null != component && null != component.parent && !(component.parent is IPage)){
				page = findControlPage(UIComponent(component.parent));
			}
			if (null != component && null != component.parent && (component.parent is IPage)){
				page = IPage(component.parent);
			}
			return page;
		}
	}
}